<template>
  <div class="main flex flex-col gap-6">
    <div class="user-info">
      <div class="info-item">
        <div class="top">
          <el-icon><User /></el-icon>
          <span>用户</span>
        </div>
        <div class="bottom">{{ info?.username || "--" }}</div>
      </div>
      <div class="info-item">
        <div class="top">
          <el-icon><Coin /></el-icon>
          <span>余额</span>
        </div>
        <div class="bottom">{{ info?.pointsBalance || "--" }}</div>
      </div>
      <div class="info-item">
        <div class="top">
          <el-icon><View /></el-icon>
          <span>状态</span>
        </div>
        <div class="bottom">{{ statusObj[info?.status] || "--" }}</div>
      </div>
    </div>
    <Balances v-if="hasPerms('管理员')" />
    <div v-loading="loading" class="flex gap-4 flex-wrap">
      <div
        v-for="item in serviceList"
        :key="item.path"
        class="flex-grow p-8 bg-white border border-gray-200 shadow-sm hover:shadow-md transition-[box-shadow,transform] duration-150 ease-out hover:scale-105 rounded-md"
      >
        <div class="text-xl font-bold flex items-center gap-2">
          <img
            class="w-[40px]"
            :src="taskConfigStore.getIcon(item.serviceList) || defaultImg"
          />
          {{ item.meta.otherName }}
        </div>
        <!-- 子项列表：这里是重点 -->
        <div class="flex flex-wrap gap-4 mt-4 text-sm">
          <div
            v-for="chunk in chunkedChildren(item.children, 3)"
            :key="chunk[0].path"
            class="grid grid-rows-3 gap-4"
          >
            <div v-for="it in chunk" :key="it.path" class="flex gap-2">
              <span
                class="hover:text-[#409EFF] cursor-pointer"
                @click="goLink(it.meta.standardCode)"
              >
                {{ it.meta.displayName }}
              </span>
              <span class="text-[#409EFF]">
                {{ multiply(it.meta.price, 10000) }} / 万条
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <FloatingService />
  </div>
</template>

<script lang="ts" setup>
import { User, Coin, View } from "@element-plus/icons-vue";
import { computed, ref, onMounted } from "vue";
import {
  toPascalCase,
  classifyByGroupWithPaths,
  groupType
} from "@/router/utils";
import { useRouter } from "vue-router";
import { useUserStoreHook } from "@/store/modules/user";
import { multiply } from "@/utils/tools";
import { getUserServiceTypes } from "@/api/globalConfigApi";
import FloatingService from "@/layout/components/FloatingService.vue";
import { hasPerms } from "@/utils/auth";
import Balances from "./Balances.vue";
import { useTaskConfigHook } from "@/store/modules/taskConfig";
import defaultImg from "@/assets/user.jpg";

const taskConfigStore = useTaskConfigHook();
const userStore = useUserStoreHook();
const router = useRouter();
const info = computed(() => userStore.currentUser?.user);
const statusObj = {
  ENABLED: "正常"
};
// 定义一个接口，描述数据项的结构
interface Item {
  id: number;
  standardCode: string;
  displayName: string;
  displayImage: string | null;
  price: number;
  hasPermission: boolean;
}

function chunkedChildren(list, size = 3) {
  const chunks = [];
  for (let i = 0; i < list.length; i += size) {
    chunks.push(list.slice(i, i + size));
  }
  return chunks;
}
// 排序方法：先根据displayName中是否包含 "tg" 和 "ws" 判断优先级，然后如果优先级相同，就按displayName的字母顺序排序
function sortItems(items: Item[]): Item[] {
  // 辅助函数：判断每个元素的优先级
  function getPriority(item: Item): number {
    const lowerName = item.displayName.toLowerCase();
    if (lowerName.includes("tg")) {
      return 0; // 优先级最高：包含 "tg"
    } else if (lowerName.includes("ws")) {
      return 1; // 第二优先级：包含 "ws"
    } else {
      return 2; // 其他情况
    }
  }

  const showTag = ["tg", "ws"];
  const hideTag = ["TG筛选开通", "TG筛用户名"];
  const filteredItems = items.filter(item => {
    return showTag.some(
      tag =>
        item.displayName.toLowerCase().includes(tag) &&
        !hideTag.some(htag => item.displayName === htag)
    );
  });

  // 排序规则：先比较优先级，相同则按displayName字母排序
  filteredItems.sort((a, b) => {
    const prioA = getPriority(a);
    const prioB = getPriority(b);

    if (prioA !== prioB) {
      return prioA - prioB;
    } else {
      return a.displayName.localeCompare(b.displayName);
    }
  });

  return filteredItems;
}
const goLink = (code: string) => {
  const name = toPascalCase(code);
  if (router.hasRoute(name) && (hasPerms("普通用户") || hasPerms("代理商"))) {
    router.push({ name });
  }
};
defineOptions({
  name: "Welcome"
});
const serviceList = ref([]);
const loading = ref(true);
getUserServiceTypes()
  .then(({ data }) => {
    // 降序排序
    const list = [...data].sort((a, b) => b.sortOrder - a.sortOrder);
    serviceList.value = classifyByGroupWithPaths(list, groupType).map(item => {
      return {
        ...item,
        serviceList: item.children.map(child => child.meta.standardCode)
      };
    });
  })
  .finally(() => {
    loading.value = false;
  });
</script>
<style scoped lang="scss">
.main {
  width: calc(100% - 48px);
  height: calc(100% - 48px);
  box-sizing: border-box;
  padding: 20px 100px;
  background-color: #fff;
  overflow-y: auto;
}
.user-info {
  display: flex;
  align-items: center;
  justify-content: space-around;
  .info-item {
    width: 300px;
    padding: 20px;
    border: 1px solid transparent;
    border-radius: 10px;
    transition: all 0.3s;
    cursor: pointer;
    &:hover {
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
      border-color: #409eff;
    }

    .top {
      border-bottom: 1px solid var(--el-border-color);
      display: flex;
      align-items: center;
      gap: 10px;
      font-weight: bold;
      padding: 10px;
      .el-icon {
        color: var(--el-color-primary);
        font-size: 22px;
      }
      span {
        font-size: 14px;
      }
    }
    .bottom {
      margin-top: 12px;
      font-size: 28px;
      font-weight: bold;
      //缩进
      text-indent: 20px;
    }
  }
}
</style>
